package com.bgs.eat.fileManager.service.impl;

import com.bgs.eat.config.FileConfigProperties;
import com.bgs.eat.fileManager.entity.FileEntity;
import com.bgs.eat.fileManager.mapper.FileMapper;
import com.bgs.eat.fileManager.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    FileConfigProperties fileConfigProperties;

    @Autowired
    FileMapper fileMapper;

    /**
     * 附件上传
     * @param file
     * @return
     */
    @Override
    public Integer uniUploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename(); //获取文件名称
            String fileSuffix = fileName.substring(fileName.indexOf(".")); //获取文件后缀
            Date date = new Date();//创建初始化格式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String newDate = simpleDateFormat.format(date);
            long fileFullSize = file.getSize();//获取文件大小
            UUID uuid = UUID.randomUUID();
            String fileFullPath = ""; //用于存放附件路径
            String mPath = "";
            String fen = uuid + fileSuffix; //用于存放附件加密文件
            //判断文件类型
            FileEntity fileEntity = new FileEntity();
            //文件根路径
            String rootPath = fileConfigProperties.getRootPath();
            if(fileConfigProperties.getImageType().contains(fileSuffix)){
                String imagePath = fileConfigProperties.getImagePath();
                long imageSize = fileConfigProperties.getImageMaxSize() * 1024 * 1024;
                //检测文件大小
                if(fileFullSize > 0 && fileFullSize <= imageSize){
                    mPath = imagePath + newDate;
            }else {
                return 0;
            }
        }else if(fileConfigProperties.getFileType().contains(fileSuffix)){
            String filePath = fileConfigProperties.getFilePath();
            long fileMaxSize = fileConfigProperties.getFileMaxSize() * 1024 * 1024;
            //检测文件大小
            if(fileFullSize > 0 && fileFullSize <= fileMaxSize){
                mPath = filePath + newDate;
            }else {
                return 0;
            }
        }
        else if(fileConfigProperties.getAudioType().contains(fileSuffix)){
            String filePath = fileConfigProperties.getAudioPath();
            long fileMaxSize = fileConfigProperties.getAudioMaxSize() * 1024 * 1024;
            //检测音频大小
            if(fileFullSize > 0 && fileFullSize <= fileMaxSize){
                mPath = filePath + newDate;
            }else {
                return 0;
            }
        }

        //将附件信息封装进实体类
        fileEntity.setFileName(fileName);
        fileEntity.setFileSize(fileFullSize);
        fileEntity.setFileSuffix(fileSuffix);
        fileEntity.setFileEncryptionName(fen);
        fileEntity.setFilePath(mPath);
        fileEntity.setDelFlag(1);
        fileEntity.setCreateTime(new Date());
        fileEntity.setUpdateTime(new Date());
        Integer flag = fileMapper.uploadFile(fileEntity);
        if(flag > 0){
            //附件绝对路径
            fileFullPath = rootPath + mPath + File.separator + fen;
            //文件存放路径
            File newFile = new File(fileFullPath);
            try {
                //判断是否传输目录是否存在
                if(!newFile.getParentFile().exists()){
                    //创建文件路径
                    newFile.getParentFile().mkdirs();
                }
                file.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            return 0;
        }

        return fileEntity.getId();
    }

    /**
     * 附件上传
     * @param multipartRequest
     * @return
     */
    @Override
    public Integer uploadFile(MultipartRequest multipartRequest) {
        MultipartFile file = multipartRequest.getFile("file");
        String fileName = file.getOriginalFilename(); //获取文件名称
        String fileSuffix = fileName.substring(fileName.indexOf(".")); //获取文件后缀
        Date date = new Date();//创建初始化格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String newDate = simpleDateFormat.format(date);
        long fileFullSize = file.getSize();//获取文件大小
        UUID uuid = UUID.randomUUID();
        String fileFullPath = ""; //用于存放附件路径
        String mPath = "";
        String fen = uuid + fileSuffix; //用于存放附件加密文件
        //判断文件类型
        FileEntity fileEntity = new FileEntity();
        //文件根路径
        String rootPath = fileConfigProperties.getRootPath();
        if(fileConfigProperties.getImageType().contains(fileSuffix)){
            String imagePath = fileConfigProperties.getImagePath();
            long imageSize = fileConfigProperties.getImageMaxSize() * 1024 * 1024;
            //检测文件大小
            if(fileFullSize > 0 && fileFullSize <= imageSize){
                mPath = imagePath + newDate;
            }else {
                return 0;
            }
        }else if(fileConfigProperties.getFileType().contains(fileSuffix)){
            String filePath = fileConfigProperties.getFilePath();
            long fileMaxSize = fileConfigProperties.getFileMaxSize() * 1024 * 1024;
            //检测文件大小
            if(fileFullSize > 0 && fileFullSize <= fileMaxSize){
                mPath = filePath + newDate;
            }else {
                return 0;
            }
        }
        else if(fileConfigProperties.getAudioType().contains(fileSuffix)){
            String filePath = fileConfigProperties.getAudioPath();
            long fileMaxSize = fileConfigProperties.getAudioMaxSize() * 1024 * 1024;
            //检测音频大小
            if(fileFullSize > 0 && fileFullSize <= fileMaxSize){
                    mPath = filePath + newDate;
            }else {
                return 0;
            }
        }

        //将附件信息封装进实体类
        fileEntity.setFileName(fileName);
        fileEntity.setFileSize(fileFullSize);
        fileEntity.setFileSuffix(fileSuffix);
        fileEntity.setFileEncryptionName(fen);
        fileEntity.setFilePath(mPath);
        fileEntity.setDelFlag(1);
        fileEntity.setCreateTime(new Date());
        fileEntity.setUpdateTime(new Date());
        Integer flag = fileMapper.uploadFile(fileEntity);
        if(flag > 0){
            //附件绝对路径
            fileFullPath = rootPath + mPath + File.separator + fen;
            //文件存放路径
            File newFile = new File(fileFullPath);
            try {
                //判断是否传输目录是否存在
                if(!newFile.getParentFile().exists()){
                    //创建文件路径
                    newFile.getParentFile().mkdirs();
                }
                file.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            return 0;
        }

        return fileEntity.getId();
    }

    /**
     * 根据Id获取图片
     * @param response
     * @param id
     */
    @Override
    public void getImageById(HttpServletResponse response,Integer id) {
        //根据Id获取该图片的信息
        FileEntity fileEntity = fileMapper.getImageById(id);
        if(fileEntity != null){
            //获取附件全路径
            String fullPath = fileConfigProperties.getRootPath()+fileEntity.getFilePath()+File.separator+fileEntity.getFileEncryptionName();
            //创建FileInputStream文件输入流
            FileInputStream fileInputStream = null;
            //创建OutputStream文件输出流
            OutputStream outputStream = null;
            try {
                File file = new File(fullPath); //创建file对象
                fileInputStream = new FileInputStream(file);
                byte[] data = new byte[(int) file.length()]; //创建byte字节数组
                fileInputStream.read(data); //将文件流读取到data字节数组当中
                outputStream = response.getOutputStream(); //获取输出流
                response.setHeader("Cache-Control","max-age=31536000, must-revalidate");
                if (fileEntity.getFileSuffix().equals(".mp4")){
                    response.setContentType("video/mpeg4");
                } else if(fileEntity.getFileSuffix().equals(".mp3")) {
                    response.setContentType("audio/mp4");
                    response.setHeader("Accept-Ranges", "bytes");
                    long l = file.length() - 1;
                    response.setHeader("Content-Range", "bytes 0-"+ l + "/" + file.length());
                } else {
                    response.setContentType("image/jpeg;charset=utf-8"); //设置响应格式
                }
                outputStream.write(data); //将字节数组写入到输出流当中
                outputStream.flush(); //清除缓存
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fileInputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 根据id进行逻辑删除
     * @return
     */
    @Override
    public Integer deleteById(Integer avartarId) {
        return fileMapper.deleteById(avartarId);
    }


}
